﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using FirebirdSql.Data.FirebirdClient;
using acessaDB;
using Estrutura;

namespace Frame
{

    public class Util
    {
        #region variaveis_globais

        acessaDB.conectaDBFireBird fireBird = new conectaDBFireBird();
        string conectionString = System.Configuration.ConfigurationManager.AppSettings["FireBirdConnectionLocal"];

        #endregion

        public Util()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static string retonarAspas(string valor, bool padraoPersistir = false)
        {
            if (string.IsNullOrEmpty(valor))
            {
                if (!padraoPersistir)
                    return "''";
                else
                    return "NULL";
            }

            return "'" + valor + "'";
        }

        public static string retonarNull(string valor)
        {
            if (valor == null)
                return "NULL";
            else if (string.IsNullOrEmpty(valor))
                return "NULL";
            else
                return valor;
        }

        public static string formataData(DateTime data, string pFormato = "MM/dd/yyyy")
        {
            //"MM/dd/yyyy" formato padrão do fireBird
            string day = data.Day.ToString();
            string mon = data.Month.ToString();
            string yea = data.Year.ToString();

            string dtRetorno = mon + "/" + day + "/" + yea;

            if (pFormato == "MM/dd/yyyy")
                return dtRetorno;
            else if (pFormato == "dd/MM/yyyy")
            {
                return day + "/" + mon + "/" + yea;
            }
            else
                return data.ToString("MM/dd/yyyy");
        }

        public static string formataReal2Casas(string valor)
        {
            string result = valor;
            try
            {
                result = Math.Round(Convert.ToDouble(valor.Replace(".", ",")), 3).ToString("###,###.00");
            }
            catch
            {
                result = string.Empty;
            }
            return result;
        }

        public static string formataFloat(string valor, bool padraoPersistir = false)
        {
            if (string.IsNullOrEmpty(valor))
            {
                if (padraoPersistir)
                    return "NULL";
            }
            
            try
            {
                string result = valor.Replace(",", ".").Replace(".", ",");
                return result;
            }
            catch
            {
                return "NULL";
            }
            
        }

        public static string formataData(string data, string pFormato = "MM/dd/yyyy", bool retornaStringVazio = false, bool padraoPersistir = false)
        {
            string result = string.Empty;

            if (string.IsNullOrEmpty(data) && retornaStringVazio)
            {
                if (padraoPersistir)
                    result =  "NULL";
                else
                    result = string.Empty;
            }

            try
            {
                DateTime dt = Convert.ToDateTime(data);

                if (pFormato == "MM/dd/yyyy")
                    return dt.ToString("MM/dd/yyyy");
                else if (pFormato == "dd/MM/yyyy" || pFormato == "dd/MM/yyyy hh:MM:ss")
                {
                    //validar se o idioma padrão é ingles
                    if (System.Configuration.ConfigurationManager.AppSettings["culture"] == "pt-BR")
                    {
                        if (pFormato == "dd/MM/yyyy")
                            result = dt.ToString("dd/MM/yyyy");
                        else if (pFormato == "dd/MM/yyyy hh:MM:ss")
                            result = dt.ToString("dd/MM/yyyy hh:MM:ss");
                    }
                    else
                    {
                        if (pFormato == "dd/MM/yyyy")
                            result = dt.ToString("MM/dd/yyyy");
                        else if (pFormato == "dd/MM/yyyy hh:MM:ss")
                            result = dt.ToString("MM/dd/yyyy hh:MM:ss");                        
                    }
                }
                else
                    result = dt.ToString(pFormato);

                return result;
            }
            catch
            {
                return System.DateTime.Now.ToString("MM/dd/yyyy");
            }
        }

        public static string formataTelefone(string telefone, bool retornaStringVazio = false)
        {
            string result = string.Empty;

            if (string.IsNullOrEmpty(telefone) && retornaStringVazio)
                return string.Empty;
            try
            {
                if (telefone.Length == 10)
                {
                    result = "(" + telefone.Substring(0, 2) + ")";
                    result += telefone.Substring(2, 4);
                    result += "-";
                    result += telefone.Substring(5, 4);
                }
                else if (telefone.Length == 8)
                {
                    result = telefone.Substring(0, 4) + "-" + telefone.Substring(3, 4);
                }
                else
                    result = telefone;
            }
            catch
            {}
            return result;
        }

        public static string formataTime(string time, string separador = ":", bool timeLongo = false)
        {
            string result = "";

            if (string.IsNullOrEmpty(time))
                return "00:00";
            //ao receber informações do Banco, o formato é de 6 digitos 00:00:00
            else if (timeLongo)
            {
                try
                {
                    result = time.Substring(0, 5);
                }
                catch
                { result = "00:00"; }
            }
            else
            {
                //*verificar se o tempo já está formatado
                if ((time.Length != 5) && (time.LastIndexOf(":") < 0))
                    result = time.Substring(0, 2) + separador + time.Substring(2, 2);
                else
                    result = time;
            }

            return result;
        }

        public static string convertIntTime(string valor, string separador = ":")
        {
            string result = "00:00";
            if (!string.IsNullOrEmpty(valor))
            {
                result = valor;
                if (valor.Length < 5)
                    result = "0" + valor;
                result = valor.Substring(0, 2) + separador + separador.Substring(1, 2);
            }
            return result;
        }


        public static string convertDataURL(string dataURL)
        {
            string result = "";

            try
            {
                if (string.IsNullOrEmpty(dataURL))
                    result = System.DateTime.Now.ToString("dd/MM/yyyy");
                else
                {
                    string dataTemp = dataURL.Substring(0, 10);
                    dataTemp = dataTemp.Replace("-", "/");
                    result = dataTemp;
                }
            }
            catch
            { result = System.DateTime.Now.ToString("dd/MM/yyyy"); }

            return result;

        }

        public static ES_Aux parametroSistema(string parametros,
                                              string dataIni = null,
                                              string dataFim = null
            )
        {

            string sql = "";

            if (string.IsNullOrEmpty(parametros))
                return new ES_Aux();

            else if (parametros == "last_first_day")
            {
                sql = "SELECT FIRSTDAY(CURRENT_DATE), LASTDAY(CURRENT_DATE) FROM RDB$DATABASE";
            }
            else if (parametros == "dateDiff")
            {
                sql = "SELECT DATEDIFF(DAY, CAST(" + retonarAspas(formataData(dataIni)) + " AS DATE), CAST(" + retonarAspas(formataData(dataFim)) + " AS DATE) ) FROM RDB$DATABASE";
            }
            ES_Aux item = new ES_Aux();
            acessaDB.conectaDBFireBird fireBird = new conectaDBFireBird();
            string conectionString = System.Configuration.ConfigurationManager.AppSettings["FireBirdConnectionLocal"];

            FbConnection fbConexao = new FbConnection(conectionString);
            FbDataReader dr = fireBird.retornaDataReader(sql, conectionString, fbConexao);
            try
            {
                while (dr.Read())
                {
                    if (parametros == "last_first_day")
                    {
                        item.FRISTDAY = dr["FIRSTDAY"].ToString();
                        item.LASTDAY = dr["LASTDAY"].ToString();
                    }
                    else if (parametros == "dateDiff")
                    {
                        item.DATEDIFF = dr["DATEDIFF"].ToString();
                    }
                }
                return item;
            }
            finally
            {
                fireBird.fecharConexao(fbConexao);
            }
        }
    }
}